﻿using System;
using System.Collections.Generic;
using System.Text;
using Csla;
using System.Data.Odbc;
using MinaspetroLibrary.Configuracoes;
using System.Data;
using Csla.Data;

namespace MinaspetroLibrary.CurriculoPack
{

    [Serializable()]
    public class Curso : BusinessBase<Curso>
    {
        #region Control Properties
        [Csla.NotUndoable()]
        private bool _isEmpty = false;

        public bool IsEmpty
        {
            get { return _isEmpty; }
        }
        #endregion

        #region Business Properties and Methods

        //declare members

        private Guid _id = Guid.NewGuid();

        private Guid _idCurriculo = Guid.NewGuid();

        private String _descricao = String.Empty;
        
        private String _cidade = String.Empty;
       
        private String _cargaHora = String.Empty;
        
        private String _instituicao = String.Empty;
        
        private DateTime _dataInicio = DateTime.MinValue;
        
        private DateTime _dataFim = DateTime.Now;


        [System.ComponentModel.DataObjectField(true, true)]
        public Guid Id
        {
            get
            {
                CanReadProperty("Id", true);
                return _id;
            }
        }

        public Guid IdCurriculo
        {
            get
            {
                CanReadProperty("IdCurriculo", true);
                return _idCurriculo;
            }
            set
            {
                CanWriteProperty("IdCurriculo", true);
                if (value == null) value = Guid.NewGuid();
                if (!_idCurriculo.Equals(value))
                {
                    _idCurriculo = value;
                    PropertyHasChanged("IdCurriculo");
                }
            }
        }

        public String Descricao
        {
            get
            {
                CanReadProperty("Descricao", true);
                return _descricao;
            }
            set
            {
                CanWriteProperty("Descricao", true);
                if (value == null) value = String.Empty;
                if (!_descricao.Equals(value))
                {
                    _descricao = value;
                    PropertyHasChanged("Descricao");
                }
            }
        }

        public String Cidade
        {
            get
            {
                CanReadProperty("Cidade", true);
                return _cidade;
            }
            set
            {
                CanWriteProperty("Cidade", true);
                if (value == null) value = String.Empty;
                if (!_cidade.Equals(value))
                {
                    _cidade = value;
                    PropertyHasChanged("Cidade");
                }
            }
        }

        public String CargaHora
        {
            get
            {
                CanReadProperty("CargaHora", true);
                return _cargaHora;
            }
            set
            {
                CanWriteProperty("CargaHora", true);
                if (value == null) value = String.Empty;
                if (!_cargaHora.Equals(value))
                {
                    _cargaHora = value;
                    PropertyHasChanged("CargaHora");
                }
            }
        }

        public String Instituicao
        {
            get
            {
                CanReadProperty("Instituicao", true);
                return _instituicao;
            }
            set
            {
                CanWriteProperty("Instituicao", true);
                if (value == null) value = String.Empty;
                if (!_instituicao.Equals(value))
                {
                    _instituicao = value;
                    PropertyHasChanged("Instituicao");
                }
            }
        }



        public DateTime DataInicio
        {
            get
            {
                CanReadProperty("DataInicio", true);
                return _dataInicio;
            }
            set
            {
                CanWriteProperty("DataInicio", true);
                if (value == null) value = DateTime.Now;
                if (!_dataInicio.Equals(value))
                {
                    _dataInicio = value;
                    PropertyHasChanged("DataInicio");
                }
            }
        }

   

        public DateTime DataFim
        {
            get
            {
                CanReadProperty("DataFim", true);
                return _dataFim;
            }
            set
            {
                CanWriteProperty("DataFim", true);
                if (value == null) value = DateTime.Now;
                if (!_dataFim.Equals(value))
                {
                    _dataFim = value;
                    PropertyHasChanged("DataFim");
                }
            }
        }

        


        protected override object GetIdValue()
        {
            return _id.ToString();
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in Curso
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in Curso
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("CursoViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in Curso
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("CursoAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in Curso
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("CursoEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in Curso
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("CursoDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private Curso()
        { /* require use of factory method */ }

        public static Curso NewCurso()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Curso");
            return DataPortal.Create<Curso>();
        }

        public static Curso GetCurso(Guid id)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("Usuário não autorizado a visualizar Curso");
            return DataPortal.Fetch<Curso>(new Criteria(id));
        }

        public override Curso Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Curso");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Curso");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("Usuário não autorizado a atualizar Curso");

            return base.Save();
        }

        public static void DeleteCurso(Guid id)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Curso");
            DataPortal.Delete(new Criteria(id));
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid Id;

            public Criteria(Guid Id)
            {
                this.Id = Id;

            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            _isEmpty = false;
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteFetch(cn, criteria);
            }//using

        }

        private void ExecuteFetch(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetFetchScript(criteria);

                using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                {
                    FetchObject(dr);
                    ValidationRules.CheckRules();

                    //load child object(s)
                    FetchChildren(dr);
                }
            }//using
        }

        private String GetFetchScript(Criteria criteria)
        {
            return "SELECT Id, IdCurriculo, Descricao, Cidade, CargaHora, DataInicio, Instituicao, DataFim "
                 + "FROM cursotb WHERE Id=\"" + criteria.Id.ToString() + "\";";
        }

        private void FetchObject(SafeDataReader dr)
        {
            _isEmpty = !dr.Read();
            if (_isEmpty) return;

            _id = new Guid(dr["Id"].ToString());
            _idCurriculo = new Guid(dr["IdCurriculo"].ToString());
            _descricao = dr.GetString("Descricao");
            _cidade = dr.GetString("Cidade");
            _cargaHora = dr.GetString("CargaHora");
            _dataInicio = dr.GetDateTime("DataInicio");
            _instituicao = dr.GetString("Instituicao");
            _dataFim = dr.GetDateTime("DataFim");

        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteInsert(cn);

                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Insert - cursotb - Id: " + _id.ToString());
        }

        private void ExecuteInsert(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetInsertScript();

                cm.ExecuteNonQuery();



            }//using
        }

        private String GetInsertScript()
        {
            return "INSERT INTO cursotb(Id, IdCurriculo, Descricao, Cidade, CargaHora, DataInicio, Instituicao, DataFim) VALUES (\""
                + _id.ToString() + "\", \""
                + _idCurriculo.ToString() + "\", \""
                + _descricao.ToString() + "\", \""
                + _cidade.ToString() + "\", \""
                + _cargaHora.ToString() + "\", \""
                + _dataInicio.ToString("yyyy-MM-dd HH:mm:ss") + "\", \""
                + _instituicao.ToString() + "\", \""
                + _dataFim.ToString("yyyy-MM-dd HH:mm:ss") + "\")";
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                if (base.IsDirty)
                {
                    ExecuteUpdate(cn);
                }

                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Update - cursotb - Id: " + _id.ToString());
        }

        private void ExecuteUpdate(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetUpdateScript();

                if (cm.ExecuteNonQuery() == 0)
                    throw new Exception("Este registro foi editado por outro usuario.");
            }//using
        }

        private String GetUpdateScript()
        {
            return "Update cursotb set "
                    + "Descricao=\"" + _descricao.ToString() + "\", "
                    + "Cidade=\"" + _cidade.ToString() + "\", \""
                    + "Descricao=\"" + _descricao.ToString() + "\", \""
                    + "CargaHora=\"" + _cargaHora.ToString() + "\", \""
                    + "DataInicio=\"" + _dataInicio.ToString("yyyy-MM-dd HH:mm:ss") + "\", \""
                    + "Instituicao=\"" + _instituicao.ToString() + "\", \""
                    + "DataFim=\"" + _dataFim.ToString("yyyy-MM-dd HH:mm:ss") + "\" "
                    + "WHERE Id=\"" + _id.ToString() + "\";";
        }

        private void UpdateChildren(OdbcConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_id));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteDelete(cn, criteria);

            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Delete - cursotb - Id: " + _id.ToString());
        }

        private void ExecuteDelete(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = cm.CommandText = "DELETE from cursotb WHERE Id=\"" + criteria.Id.ToString() + "\";";

                cm.ExecuteNonQuery();
            }//using
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
